package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.bean.BeanUtil;
import com.budwk.app.jim.SqfwWebSocket;
import com.budwk.app.jim.WebSocketMsgDTO;
import com.budwk.app.sqfw.component.PushMsgComponent;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.dto.SqfwCopyRecordMultiDTO;
import com.budwk.app.sqfw.models.Sqfw_copyRecord;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.services.SqfwCopyrecordService;
import com.budwk.app.sqfw.services.SqfwPushMsgLogService;
import com.budwk.app.sqfw.services.SqfwServicerecordService;
import com.budwk.app.sqfw.vo.UserCopyRecordUserVO;
import com.budwk.app.sqfw.vo.UserCopyRecordVO;
import com.budwk.app.sqfw.vo.UserServiceOrderVO;
import com.budwk.app.sqfw.vo.pushmsg.PushMsgConfigVo;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.constant.RedisConstant;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class SqfwCopyrecordServiceImpl extends BaseServiceImpl<Sqfw_copyRecord> implements SqfwCopyrecordService {
    public SqfwCopyrecordServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private SqfwWebSocket sqfwWebSocket;
    @Inject
    private SqfwCopyrecordService sqfwCopyrecordService;
    @Inject
    private RedisService redisService;
    @Inject
    private SqfwPushMsgLogService sqfwPushMsgLogService;

    @Override
    public int createMulti(SqfwCopyRecordMultiDTO multiDTO) {
        List<String> toUserIdList = multiDTO.getToUserIds();

        int insertCount = 0;
        for (String toUserId : toUserIdList) {
            Sqfw_copyRecord copyRecord = new Sqfw_copyRecord();
            BeanUtil.copyProperties(multiDTO, copyRecord);

            copyRecord.setToUserId(toUserId);
            copyRecord.setCreateDate(new Date());
            copyRecord.setUpdateDate(new Date());
            copyRecord.setUpdateBy(multiDTO.getCopyUserid());
            copyRecord.setReadFlag(false);
            copyRecord.setDelFlag(false);
            insert(copyRecord);
            insertCount++;

            WebSocketMsgDTO msgDTO = new WebSocketMsgDTO(SqfwWebSocketMsgConstants.copy_record_created, "有新的消息抄送");

            // 添加服务记录id
            Map<String, Object> relatedParamMap = Maps.newHashMap();
            relatedParamMap.put(SqfwWebSocketMsgConstants.service_record_id, copyRecord.getSqfwId());

            // 添加抄送人名字
            String copyUserId = copyRecord.getCopyUserid();
            Sys_user copyUser = sysUserService.fetch(copyUserId);
            relatedParamMap.put(SqfwWebSocketMsgConstants.service_record_create_by_name, copyUser.getUsername());

            msgDTO.setRelatedParams(relatedParamMap);
            sqfwWebSocket.sendMessage(toUserId, msgDTO);

            //发送消息推送
            //获取token
            if (!StringUtils.isNotBlank(copyRecord.getToUserId())) {
                continue;
            }
            String toCopyUserId = copyRecord.getToUserId();
            Sys_user toCopyUser = sysUserService.fetch(toCopyUserId);
            if (redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname()).isEmpty()) {
                continue;
            }
            if (redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname()).get("pushToken").equals("null")) {
                continue;
            }
            if (redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname()).get("pushToken").equals("")) {
                continue;
            }
            Map mapToken = redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname());
            // 发送消息
            PushMsgConfigVo c = PushMsgComponent.buildPushMsgConfigVo(mapToken, multiDTO.getSqfwId(), "msg_cc", null);
            sqfwPushMsgLogService.pushMessage(c, copyUser, null);
        }

        // 修改服务记录里面的copyName和copyPhone
        List<Sys_user> sendUserList = sysUserService.query(Cnd.where("id", "in", multiDTO.getToUserIds()));
        List<String> userNameList = Lists.newArrayList();
        List<String> userPhoneList = Lists.newArrayList();
        for (Sys_user sysUser : sendUserList) {
            userNameList.add(sysUser.getUsername());
            userPhoneList.add(sysUser.getLoginname());
        }

        String serviceName = Joiner.on(",").join(userNameList);
        String servicePhone = Joiner.on(",").join(userPhoneList);

        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(multiDTO.getSqfwId());

        if (StringUtils.isNotBlank(serviceRecord.getCopyName())) {
            if (StringUtils.isNotBlank(serviceName)) {
                serviceRecord.setCopyName(serviceRecord.getCopyName() + "," + serviceName);
                serviceRecord.setCopyPhone(serviceRecord.getCopyPhone() + "," + servicePhone);
            } else {
                serviceRecord.setCopyName(serviceRecord.getCopyName());
                serviceRecord.setCopyPhone(serviceRecord.getCopyPhone());
            }
        } else {
            serviceRecord.setCopyName(serviceName);
            serviceRecord.setCopyPhone(servicePhone);
        }
        sqfwServicerecordService.update(serviceRecord);
        return insertCount;
    }


    @Override
    public int createMultiNew(SqfwCopyRecordMultiDTO multiDTO) {
        if (multiDTO.getToUserIds().size() > 0) {
            //获取新增的list
            String[] userId = multiDTO.getToUserIds().get(0).split(",");
            List<String> toUserIdList = new ArrayList<>(Arrays.asList(userId));
        /*for (int i=0;i<userId.length;i++){
            toUserIdList.add(userId[i]);
        }*/

            //获取删除的list
            List<String> delToUserIdList = new ArrayList<>();
            if (multiDTO.getToUserIds().size() >= 2) {
                String[] delUserId = multiDTO.getToUserIds().get(1).split(",");
                delToUserIdList = new ArrayList<>(Arrays.asList(delUserId));
                Cnd cnd = Cnd.NEW();
                cnd.and("sqfw_id", "=", multiDTO.getSqfwId());
                cnd.and("to_user_id", "in", delToUserIdList);
                List<Sqfw_copyRecord> lists = sqfwCopyrecordService.query(cnd);
                List<String> ids = new ArrayList<>();
                for (Sqfw_copyRecord id : lists) {
                    ids.add(id.getId());
                }
                sqfwCopyrecordService.delete(ids);
            }
        /*for (int i=0;i<delUserId.length;i++){
            delToUserIdList.add(delUserId[i]);
        }*/

            int insertCount = 0;
            for (String toUserId : toUserIdList) {
                Sqfw_copyRecord copyRecord = new Sqfw_copyRecord();
                BeanUtil.copyProperties(multiDTO, copyRecord);

                copyRecord.setToUserId(toUserId);
                copyRecord.setCreateDate(new Date());
                copyRecord.setUpdateDate(new Date());
                copyRecord.setUpdateBy(multiDTO.getCopyUserid());
                copyRecord.setReadFlag(false);
                copyRecord.setDelFlag(false);
                if (StringUtils.isNotBlank(toUserId)) {
                    insert(copyRecord);
                }
                insertCount++;
                sqfwWebSocket.sendMessage(toUserId, new WebSocketMsgDTO(SqfwWebSocketMsgConstants.copy_record_created, "有新的消息抄送"));

                //发送消息推送
                //获取token
                String copyUserId = copyRecord.getCopyUserid();
                Sys_user copyUser = sysUserService.fetch(copyUserId);

                if (!StringUtils.isNotBlank(copyRecord.getToUserId())) {
                    continue;
                }
                String toCopyUserId = copyRecord.getToUserId();
                Sys_user toCopyUser = sysUserService.fetch(toCopyUserId);
                if (redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname()).isEmpty()) {
                    continue;
                }
                if (redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname()).get("pushToken").equals("null")) {
                    continue;
                }
                if (redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname()).get("pushToken").equals("")) {
                    continue;
                }
                Map mapToken = redisService.hgetAll(RedisConstant.PRE + "push:token:" + toCopyUser.getLoginname());
                // 推送消息
                PushMsgConfigVo c = PushMsgComponent.buildPushMsgConfigVo(mapToken, multiDTO.getSqfwId(), "msg_cc", null);
                sqfwPushMsgLogService.pushMessage(c, copyUser, null);
            }

            // 修改服务记录里面的copyName和copyPhone
            List<Sys_user> sendUserList = sysUserService.query(Cnd.where("id", "in", toUserIdList));
            List<String> userNameList = Lists.newArrayList();
            List<String> userPhoneList = Lists.newArrayList();
            for (Sys_user sysUser : sendUserList) {
                userNameList.add(sysUser.getUsername());
                userPhoneList.add(sysUser.getLoginname());
            }

            List<Sys_user> delsendUserList = sysUserService.query(Cnd.where("id", "in", delToUserIdList));
            List<String> deluserNameList = Lists.newArrayList();
            List<String> deluserPhoneList = Lists.newArrayList();
            for (Sys_user sysUser : delsendUserList) {
                deluserNameList.add(sysUser.getUsername());
                deluserPhoneList.add(sysUser.getLoginname());
            }


            String serviceName = Joiner.on(",").join(userNameList);
            String servicePhone = Joiner.on(",").join(userPhoneList);


            //获取原来的姓名list
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(multiDTO.getSqfwId());

            if (StringUtils.isNotBlank(serviceRecord.getCopyName())) {
                String[] name = serviceRecord.getCopyName().split(",");
                String[] phone = serviceRecord.getCopyPhone().split(",");
                List<String> nameFomerUserList = new ArrayList<>(Arrays.asList(name));
                List<String> phoneFomerUserList = new ArrayList<>(Arrays.asList(phone));


                //合并list并去重
                Set<String> set = new HashSet<>(nameFomerUserList);
                set.addAll(userNameList);
                List<String> list = new ArrayList<>(set);

                Set<String> setphone = new HashSet<>(phoneFomerUserList);
                setphone.addAll(userPhoneList);
                List<String> phonelist = new ArrayList<>(setphone);


                HashSet hs1 = new HashSet(list);
                //删除姓名
                HashSet hs2 = new HashSet(deluserNameList);
                hs1.removeAll(hs2);
                List<String> listC = new ArrayList<String>();
                listC.addAll(hs1);


                HashSet hs3 = new HashSet(phonelist);
                //删除电话
                HashSet hs4 = new HashSet(deluserPhoneList);
                hs3.removeAll(hs4);
                List<String> listD = new ArrayList<String>();
                listD.addAll(hs3);


                String serviceNameResult = Joiner.on(",").join(listC);
                String servicePhoneResult = Joiner.on(",").join(listD);
                serviceRecord.setCopyName(serviceNameResult);
                serviceRecord.setCopyPhone(servicePhoneResult);
            } else {
                serviceRecord.setCopyName(serviceName);
                serviceRecord.setCopyPhone(servicePhone);
            }
       /* if (StringUtils.isNotBlank(serviceRecord.getCopyName())){



            if (StringUtils.isNotBlank(serviceName)){
                serviceRecord.setCopyName(serviceRecord.getCopyName()+","+serviceName);
                serviceRecord.setCopyPhone(serviceRecord.getCopyPhone()+","+servicePhone);
            }else{
                serviceRecord.setCopyName(serviceRecord.getCopyName());
                serviceRecord.setCopyPhone(serviceRecord.getCopyPhone());
            }
        }else{
            serviceRecord.setCopyName(serviceName);
            serviceRecord.setCopyPhone(servicePhone);
        }*/
            sqfwServicerecordService.update(serviceRecord);
            return insertCount;
        } else
            return 0;
    }


    @Override
    public Pagination listCopyRecord(String copyUserId, String toUserId, int pageNo, int pageSize, String pageOrderName, String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(copyUserId)) {
            cnd.or("copy_user_id", "=", copyUserId);
        }
        if (StringUtils.isNotBlank(toUserId)) {
            cnd.or("to_user_id", "=", toUserId);
        }

        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("create_date", "desc");
        }

        Pagination pagination = listPage(pageNo, pageSize, cnd);
        List<Sqfw_copyRecord> list = pagination.getList(Sqfw_copyRecord.class);

        List<String> sqfwIdList = list.stream().map(Sqfw_copyRecord::getSqfwId).collect(Collectors.toList());
        List<UserServiceOrderVO> userServiceOrderVOS = sqfwServicerecordService.listByServiceOrderIdList(sqfwIdList);

        if (userServiceOrderVOS.size() == 0) {
            pagination.setList(Lists.newArrayList());
            return pagination;
        }

        Map<String, UserServiceOrderVO> serviceRecordMap = userServiceOrderVOS.stream().collect(Collectors.toMap(UserServiceOrderVO::getId, item -> item));

        Map<String, Sys_user> sysUserIdMap = Maps.newHashMap();

        List<UserCopyRecordVO> resultList = Lists.newArrayList();
        for (Sqfw_copyRecord sqfw_copyRecord : list) {
            String sqfwId = sqfw_copyRecord.getSqfwId();

            UserCopyRecordVO userCopyRecordVO = new UserCopyRecordVO();
            BeanUtil.copyProperties(sqfw_copyRecord, userCopyRecordVO);
            userCopyRecordVO.setUserServiceOrderVO(serviceRecordMap.get(sqfwId));

            String queryCopyUserid = sqfw_copyRecord.getCopyUserid();
            String queryToUserId = sqfw_copyRecord.getToUserId();

            userCopyRecordVO.setCopyUserName(getUserName(sysUserIdMap, queryCopyUserid));
            userCopyRecordVO.setToUserName(getUserName(sysUserIdMap, queryToUserId));

            resultList.add(userCopyRecordVO);
        }

        pagination.setList(resultList);
        return pagination;
    }

    @Override
    public List<UserCopyRecordUserVO> listCopyRecordToUser(String sqfwId) {
        List<Sqfw_copyRecord> copyRecordList = query(Cnd.where("sqfw_id", "=", sqfwId));

        List<UserCopyRecordUserVO> resultList = Lists.newArrayList();

        Map<String, Sys_user> userMap = Maps.newHashMap();
        for (Sqfw_copyRecord copyRecord : copyRecordList) {

            UserCopyRecordUserVO vo = new UserCopyRecordUserVO();
            BeanUtil.copyProperties(copyRecord, vo);

            String copyUserid = copyRecord.getCopyUserid();
            String toUserId = copyRecord.getToUserId();

            vo.setToUserId(toUserId);
            vo.setToUserName(getUserName(userMap, toUserId));

            vo.setCopyUserId(copyUserid);
            vo.setCopyUserName(getUserName(userMap, copyUserid));

            resultList.add(vo);
        }

        return resultList;
    }

    private String getUserName(Map<String, Sys_user> userMap, String userId) {
        if (userMap.containsKey(userId)) {
            return userMap.get(userId).getUsername();
        } else {
            try {
                Sys_user sysUser = sysUserService.getUserById(userId);
                if (sysUser != null) {
                    userMap.put(userId, sysUser);
                    return sysUser.getUsername();
                }
            } catch (Exception ignored) {
            }
        }

        return null;
    }
}
